package aar.test.tessocr;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.EventMessage.MessageEvent;
import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.db.impl.ClientInfoDaoImp;
import aar.test.tessocr.fragment.CabinetListFragment;
import aar.test.tessocr.fragment.DepositFragment;
import aar.test.tessocr.fragment.MineFragment;
import aar.test.tessocr.model.CabinetListMpdel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.UpDateModel;
import aar.test.tessocr.model.loginModel;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.utils.Utils;
import aar.test.tessocr.view.ControlScrollViewPager;
import aar.test.tessocr.view.SearchHistoryPopwindow;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import clx.tessocr.ocreng.R;
import lib_zxing.activity.CodeUtils;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.EventMessage.MessageEvent.SEARCH_CABINET;
import static aar.test.tessocr.Login1Activity.JSON;

/**
 * Created by sunshine on 2020/7/21.
 */

public class MainActivity extends BaseActivity implements ViewPager.OnPageChangeListener, SearchHistoryPopwindow.OnSearchListener{
    @BindView(R.id.img_main_button_data)
    AppCompatImageView imgMainButtonData;
    @BindView(R.id.tv_main_button_data)
    AppCompatTextView tvMainButtonData;
    @BindView(R.id.img_main_bottom_sport)
    AppCompatImageView imgMainBottomSport;
    @BindView(R.id.tv_main_bottom_sport)
    AppCompatTextView tvMainBottomSport;
    @BindView(R.id.img_main_bottom_record)
    AppCompatImageView imgMainBottomRecord;
    @BindView(R.id.tv_main_bottom_record)
    AppCompatTextView tvMainBottomRecord;

    private List<Fragment> fragments = new ArrayList<>();
    private PageAdapter mAdapter;
    private ControlScrollViewPager vpMainContent;
    private DisplayMetrics dm;
    private long mLastClickBackTime = 0l;

    public static final String APP_KEY = "LHBKDKygBSyA7WE6rRUtLBUQ";// 替换您申请的合合信息授权提供的APP_KEY
    public static final String EXTRA_KEY_APP_KEY = "EXTRA_KEY_APP_KEY";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainpage);
        ButterKnife.bind(this);
        initView();

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        requestP();
        upDate();
        if (PrefUtils.getBoolean(MainActivity.this, "isFirstRun", true)) {
            //第一次使用app，根据账号更新其派件过的手机号列表
            upDatePhoneList();
            PrefUtils.setBoolean(MainActivity.this, "isFirstRun", false);
        }
    }

    private void upDatePhoneList() {
        Map<String ,Object> map=new HashMap<>();
        map.put("adminid",PrefUtils.getString(MainActivity.this, "userId", ""));

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON,json);
        OkGo.<LzyResponse<ArrayList<String>>>post(Urls.URL_PHONE_LIST)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<ArrayList<String>>>(MainActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<ArrayList<String>>> response) {
                        final ArrayList<String> phonelist = response.body().data;

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (null != phonelist && phonelist.size() != 0) {
                                    ClientInfoDaoImp.getInstance(MainActivity.this).deleteAll();
                                    for (int i = 0; i < phonelist.size(); i++) {
                                        ClientInfoDaoImp.getInstance(MainActivity.this).AddTelNum(phonelist.get(i));
                                    }
                                }
                            }
                        }).run();
                    }

                    @Override
                    public void onError(Response<LzyResponse<ArrayList<String>>> response) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.require_phonelist_failed), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void requestP() {
        AndPermission.with(this)
                .requestCode(ConstantPara.REQUEST_CODE_PERMISSION_SD)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.CALL_PHONE)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(MainActivity.this, rationale).
                                show();
                    }
                })
                .start();
    }

    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(MainActivity.this, "111111111111", Toast.LENGTH_SHORT).show();
                    //unZipAssset();
                    break;
                }

            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(ShowMobleSDMediaActivity.this, R.string.message_post_failed, Toast.LENGTH_SHORT).show();
                    break;
                }

            }


            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, deniedPermissions)) {

                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(MainActivity.this, ConstantPara.REQUEST_CODE_SETTING, dm).show();

                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

            }
        }
    };

    private void initView() {
        vpMainContent = (ControlScrollViewPager)findViewById(R.id.vp_main_content);
        fragments.add(DepositFragment.newInstance());
        fragments.add(CabinetListFragment.newInstance());
        fragments.add(MineFragment.newInstance());

        mAdapter = new PageAdapter(getSupportFragmentManager(), fragments);
        vpMainContent.setAdapter(mAdapter);
        vpMainContent.setOffscreenPageLimit(2);
        vpMainContent.addOnPageChangeListener(this);

        resetButton(0);
    }

    private void resetButton(int position) {
        tvMainButtonData.setTextColor(getResources().getColor(R.color.contents_text));
        tvMainBottomSport.setTextColor(getResources().getColor(R.color.contents_text));
        tvMainBottomRecord.setTextColor(getResources().getColor(R.color.contents_text));
        imgMainButtonData.setImageResource(R.mipmap.img_data_unselect);
        imgMainBottomSport.setImageResource(R.mipmap.img_sport_unselect);
        imgMainBottomRecord.setImageResource(R.mipmap.img_record_unselect);

        switch (position) {
            case 0:
                imgMainButtonData.setImageResource(R.mipmap.img_data_select);
                tvMainButtonData.setTextColor(getResources().getColor(R.color.title_background_color));
                break;
            case 1:
                imgMainBottomSport.setImageResource(R.mipmap.img_sport_select);
                tvMainBottomSport.setTextColor(getResources().getColor(R.color.title_background_color));
                break;
            case 2:
                imgMainBottomRecord.setImageResource(R.mipmap.img_record_select);
                tvMainBottomRecord.setTextColor(getResources().getColor(R.color.title_background_color));
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        resetButton(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onSearch(String searchContent) {
        EventBus.getDefault().post(new MessageEvent(SEARCH_CABINET, searchContent));
    }

    @Override
    public void onBack() {

    }

    static class PageAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragments;

        public PageAdapter(FragmentManager fm, @NonNull List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    @OnClick({R.id.rl_main_button_data, R.id.rl_main_bottom_sport, R.id.rl_main_bottom_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_main_button_data:
                vpMainContent.setCurrentItem(0);
                break;
            case R.id.rl_main_bottom_sport:
                vpMainContent.setCurrentItem(1);
                break;
            case R.id.rl_main_bottom_record:
                vpMainContent.setCurrentItem(2);
                break;
        }
    }

    private void upDate() {
        Map<String, Object> map = new HashMap<>();
        //map.put("adminid", loginCabModel.getId());

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<UpDateModel>>post(Urls.URL_UPDATE)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<UpDateModel>>(MainActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<UpDateModel>> response) {
                        UpDateModel upDateModel = response.body().data;
                        String url = upDateModel.getUrl();
                        int newVersion = upDateModel.getVersion();
                        int currVersion = 0;
                        try {
                            currVersion = Utils.getVersionCode(MainActivity.this);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (Utils.canUpdate(newVersion, currVersion)) {
                            //Utils.downLoadApk(mContext, url);
                            updateRemind(MainActivity.this, url, "bug修复");
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<UpDateModel>> response) {
                        Log.e("MainActivity", "onError---------------------");
                    }
                });
    }

    /**
     * 版本更新提示框
     */
    public static void updateRemind(final Activity activity,
                                    final String apkPath, String updateInfo) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(activity,
                R.style.DialogStyle).setTitle(
                activity.getString(R.string.etalk_update_remind)).setMessage(
                updateInfo);

        dialog.setPositiveButton(activity.getString(R.string.etalk_updata_now),
                new AlertDialog.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // new DownThread().start();

                        if (!TextUtils.isEmpty(apkPath)) {
                            try {
                                Intent it = new Intent(Intent.ACTION_VIEW, Uri
                                        .parse(apkPath));
                                // it.setClassName("com.android.browser","com.android.browser.BrowserActivity");
                                activity.startActivity(it);
                            } catch (Exception e) {
                                Toast.makeText(activity, activity
                                        .getString(R.string.text_download_path), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(activity, activity
                                    .getString(R.string.text_download_path), Toast.LENGTH_SHORT).show();
                        }

                    }
                });

        dialog.setNegativeButton(
                activity.getString(R.string.etalk_updata_wait),
                new AlertDialog.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                    }
                });
        dialog.show();
    }

    @Override
    public void onBackPressed() {
        long nowTime = System.currentTimeMillis();
        if (nowTime - mLastClickBackTime < 1000 * 2) {
            PrefUtils.setString(MainActivity.this, "cabinetCode", "无");
            PrefUtils.setBoolean(MainActivity.this, "cabinetLoginFlag", false);
            PrefUtils.setString(MainActivity.this, "cabinetId", "");
            finish();
            super.onBackPressed();
        } else {
            Toast.makeText(this, getText(R.string.confirm_double_click_quit), Toast.LENGTH_SHORT).show();
        }
        mLastClickBackTime = nowTime;
    }
}
